package com.glela.task;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import com.glela.common.util.YeePayAESUtil;
import com.glela.common.util.YeePayDigest;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.talent.util.MyDateUtil;
import com.glela.usermoney.mapper.YeepayDivideMapper;
import com.glela.usermoney.model.YeepayDivide;

/**
 * 易宝相关任务导出
 * @author gwq
 */
public class YeePayTask {
	
	private static final Logger logger = LoggerFactory.getLogger(OrderTask.class);
	private static MyDateUtil DateUtil = MyDateUtil.INSTANCE;
	@Autowired
	private YeepayDivideMapper yeepayDivideMapper;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	/**
	 * <dl>
	 * <dt>导出前一天的分账信息</dt>
	 * @Scheduled(cron = "0 0 10 * * ?")//每天早上10点执行一次
	 * </dl>
	 * @author gaoweiqi
	 * @date 2017年11月22日 16:44:05
	 */
	public void saveYeePayDivide() {
		// keyForHmac – 商户密钥
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("authorize_secret_key");
		if(baseRestrictions == null || StringUtils.isBlank(baseRestrictions.getName())) {
			logger.error("未配置账户密钥:authorize_secret_key");
		}
		String keyForHmac = baseRestrictions.getName();
		// AESUtil加密与解密的密钥，截取商户密钥的前16位
		String keyForAes = keyForHmac.substring(0, 16);
		baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("authorize_no");
		if(baseRestrictions == null || StringUtils.isBlank(baseRestrictions.getName())) {
			logger.error("未配置商户账号:authorize_no");
		}
		String operator_no = baseRestrictions.getName();
		String checkDate =DateUtil.getOldDays(1).split(" ")[0];//前一天 
		String orderType = "divide";
		String fileType = "txt";
		Map<String, String> map = new HashMap<String, String>();
		map.put("operator_no", operator_no);
		map.put("checkDate", checkDate);
		map.put("orderType", orderType);
		map.put("fileType", fileType);
		String source = operator_no + checkDate + orderType;
		String[] stringArray = { operator_no, checkDate, orderType };
		String hmac = YeePayDigest.getHmac(stringArray,keyForHmac);
		map.put("hmac", hmac);
		String jsonString = JSON.toJSONString(map);
		String certify_token = YeePayAESUtil.encrypt(jsonString, keyForAes);
		String authorize_no = operator_no;
		String parameterData = "authorize_no=" + authorize_no
				+ "&certify_token=" + certify_token;
		baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("downloadOrderDocument");
		if(baseRestrictions == null || StringUtils.isBlank(baseRestrictions.getName())) {
			logger.error("未配置请求分账信息的地址:downloadOrderDocument");
		}
		String url =baseRestrictions.getName();
		URL localURL;
		try {
			localURL = new URL(url);
			URLConnection connection = localURL.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod("POST");// 请求方式为POST
			httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Content-Length",
					String.valueOf(parameterData.length()));
			OutputStream outputStream = null;
			OutputStreamWriter outputStreamWriter = null;
			InputStream inputStream = null;
			outputStream = httpURLConnection.getOutputStream();
			outputStreamWriter = new OutputStreamWriter(outputStream);
			outputStreamWriter.write(parameterData.toString());
			outputStreamWriter.flush();
			logger.info("Response code is "+ httpURLConnection.getResponseCode());
			if (httpURLConnection.getResponseCode() != 200) {
				throw new Exception(
						"HTTP Request is not success, Response code is "
								+ httpURLConnection.getResponseCode());
			}
			inputStream = httpURLConnection.getInputStream();
			FileOutputStream fos = null;
			String full_filename = null;
			String dir = null;
			if (StringUtils.isBlank(fileType)) {
				fileType = "txt";
			}
			full_filename = "orderExcel/orderData." + fileType;
			dir = full_filename.substring(0, full_filename.lastIndexOf("/"));
			File path = new File(dir);
			if (!path.exists()) {
				path.mkdirs();
			}
			fos = new FileOutputStream(full_filename);
			BufferedInputStream bis = new BufferedInputStream(inputStream);
			byte[] by = new byte[1024];
			while (true) {
				int i = bis.read(by);
				if (i == -1) {
					break;
				}
				fos.write(by, 0, i);
			}
			// 关闭文件流
			fos.close();
			// 读取文件信息到数据库
			readYeePayFileToDB(full_filename, orderType, checkDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 读取易宝的记账文件到数据库
	 * 
	 * @author gaoweiqi
	 * @throws Exception
	 * @date 2017年11月22日 12:44:05
	 * 
	 **/
	public void readYeePayFileToDB(String File, String Type,
			String fileCreateTime) throws Exception {
		File FilePath = new File(File);
		if (!FilePath.exists()) {
			logger.error("未找到易宝文件");
			return;
		}
		switch (Type) {
		case "divide":
			List<String> listLine = FileUtils.readLines(FilePath);
			if (listLine != null && listLine.size() > 2) {
				List<YeepayDivide> list = new ArrayList<YeepayDivide>();
				for (int i = 1; i < listLine.size() - 1; i++) {
					// 写入数据库
					YeepayDivide divideTemp = createYeepayDivide(listLine.get(i)+fileCreateTime+",");
					if(divideTemp!=null){
						list.add(divideTemp);
					}
				}
				yeepayDivideMapper.batchInsert(list);
			}
			break;
		default:
			logger.error("未找到对应的易宝文件类型");
			return;
		}
		// 删除临时文件
		FileUtils.deleteDirectory(new File(File.substring(0,
				File.lastIndexOf("/"))));
	}
	/**
	 * 转化分账对象
	 * @author gaoweiqi
	 * @date 2017年11月22日 12:44:05
	 * 
	 **/
	public   YeepayDivide createYeepayDivide(String str) {
		try {
			String[]  strs=str.split(",");
			return new YeepayDivide(0L, strs[0], strs[1], strs[2], strs[3],strs[4],
			strs[5],null, null, strs[6], strs[7], strs[8]);
		} catch (Exception e) {
			logger.error("解析分账信息错误:"+str+e.getMessage());
		}
		return null;
	}
}
